package com.guet.config;

import com.guet.pojo.User;
import com.guet.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author MicahYin
 * @date 2020/8/10 15:55
 */
//自定义的UserRealm类
public class UserRealm extends AuthorizingRealm{
    @Autowired
    UserService userService;
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了=>授权doGetAuthorizationInfo");
        //在此处对用户进行授权
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        //拿到当前登录的这个对象
        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User)subject.getPrincipal();//拿到user对象，这个对象是由下面的那个方法传过来的
        //从数据库中查出真实的用户权限
        info.addStringPermission(currentUser.getPerms());
        return info;
    }
    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了=>认证doGetAuthorizationInfo");
        //用户名和密码

        UsernamePasswordToken userToken=(UsernamePasswordToken)authenticationToken;
        User user = userService.queryUserByName(userToken.getUsername());
        if (user==null){//没有这个用户
            return null;//返回null，抛出异常，UnknownAccountException
        }
        //密码认证，交给shrio去做,此处可以采用密码加密
        //在这里将user传到上面的方法，供上面的方法调用，不必再查数据库
        return new SimpleAuthenticationInfo(user,user.getPwd(),"");
    }
}
